/*
 * @Author: your name
 * @Date: 2021-12-21 17:40:31
 * @LastEditTime: 2021-12-21 21:37:38
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /project_am/am-server/app/service/course.js
 */
const { Service } = require('egg')
const BussinessError = require('../utils/BussinessError')

class CourseService extends Service {
    async saveOrUpdate (row) {
        const { mysql } = this.app
        try {
          if (row.id) {
            // 更新 {id:1,name:"terry",no:2021110022}  update school_course set name='terry',no=2021 where id = 1
            await mysql.update('school_course', row)
          } else {
            await mysql.insert('school_course', row)
          }
        } catch (error) {
          console.log(error);
          throw new BussinessError('操作失败')
        }
      }

      async pageQuery ({ page, pageSize }) {
        const { mysql } = this.app;
        
        //1. 查询分页数据
        let sql_select = `select * from school_course limit ${(page - 1) * pageSize},${pageSize}`
        const courses = await mysql.query(sql_select)
    
        //2. 统计数量
        const sql = `select count(*) as total from school_course`
        // 获取分页查询的数据条数
        const [{ total }] = await mysql.query(sql)
        // 返回
        return {
          page,
          pageSize,
          total,
          list: courses
        }
      }

     //根据ID删除课程信息
    async deleteById (id) {
    //解构出this.app中的的mysql属性，也就是this.app.mysql
    const { mysql } = this.app
    try {
      await mysql.delete('school_course', { id })
    } catch (error) {
      throw new BussinessError('删除失败')
    }
  }
}
module.exports = CourseService;